package com.yonyou.distribute.service;

import com.yonyou.distribute.mapper.LockMapper;
import com.yonyou.distribute.pojo.Lock;
import com.yonyou.distribute.zk.ZKDistributedLock_3;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * mysql 实现分布式锁
 */
@Service
public class MysqlDistributedService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private LockMapper lockMapper;

    public void deduct() throws InterruptedException {
        try {
            // 加锁
            Lock lock = new Lock();
            lock.setLockName("lock");
            this.lockMapper.insert(lock);
            // 1、查询库存
            String stock = this.stringRedisTemplate.opsForValue().get("stock");
            // 2、判断库存是否充足
            if(!StringUtils.isEmpty(stock)){
                Integer st = Integer.valueOf(stock);
                if(st > 0){
                    //3、更新库存到数据库
                    this.stringRedisTemplate.opsForValue().set("stock", String.valueOf(--st));
                }
            }
            // 解锁
            this.lockMapper.deleteById(lock.getId());
        } catch (Exception e) {
            e.printStackTrace();
            // 重试
            TimeUnit.SECONDS.sleep(50);
            this.deduct();
        }
    }
}
